package com.hfh.management.comments;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementSetter;
import org.springframework.stereotype.Service;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by yzYang on 2014/12/13.
 */
@Service
public class CommentsDaoImpl implements CommentsDao{

    @Autowired
    private JdbcTemplate jdbcTemplate;

    /*@Override
    public List<CusComment> getCommentsList(String pageIndex) {
        String sql = "SELECT * from t_cuscomments ORDER BY cdatetime DESC LIMIT ?,10";
        List<CusComment> acs = jdbcTemplate.query(sql,new Object[]{pageIndex},new CusCommentRowMapper());
        return acs;
    }*/

    @Override
    public Map<String,Object> getCommentsList(String pageIndex) {
        Map<String,Object> map = new HashMap<String, Object>();
        String total_sql =  "select ceil(count(*) from t_cuscomments ";
        int total =jdbcTemplate.queryForObject(total_sql,Integer.class);
        String sql = "SELECT * from t_cuscomments ORDER BY cdatetime DESC LIMIT ?,10";
        List<CusComment> acs = jdbcTemplate.query(sql,new Object[]{pageIndex},new CusCommentRowMapper());
        map.put("total",total);
        map.put("data",acs);
        return map;
    }

    @Override
    public Map<String,Object> getCommentsList(String pageIndex,int pagesize) {
        int sql_page_index = Integer.parseInt(pageIndex);
        int sql_page_size = pagesize;
        Map<String,Object> map = new HashMap<String, Object>();
        String total_sql =  "select ceil(count(*)/"+sql_page_size+") from t_cuscomments ";
        int total =jdbcTemplate.queryForObject(total_sql,Integer.class);

        StringBuilder sb = new StringBuilder("SELECT * from t_cuscomments ORDER BY cdatetime DESC LIMIT ");
        sb.append(sql_page_index).append(", ").append(sql_page_size);
        List<CusComment> acs = jdbcTemplate.query(sb.toString(),new CusCommentRowMapper());
        map.put("total",total);
        map.put("data",acs);
        return map;
    }


    @Override
    public boolean saveComment(final String ccontent, final String name) {
        String sql = "INSERT INTO t_cuscomments(cusname,cuscontent,cdatetime)VALUES(?,?,NOW())";
        int r = jdbcTemplate.update(sql, new PreparedStatementSetter() {
        public void setValues(PreparedStatement ps) throws SQLException {
            ps.setString(1, name);
            ps.setString(2,ccontent);
        }
    });
        return r>0?true:false;
    }
}
